<template>
  <div class="login-wrapper" ref="login">
    <div class="nav-wrapper">
      <div class="left-logo">
        <img v-if="logoObj.logoImg" :src="logoObj.logoImg" alt />
        <img v-else src="../assets/img/logo.svg" />
        <div class="logo-title">
          <span class="left-border"></span>
          <span>{{logoObj.platformName || '停车运营管理平台'}}</span>
          <span class="title-version">{{version}}</span>
        </div>
      </div>
      <div class="right-nav">
        <div class="nav-item" :class="{ active: loginType== 0 }" @click="loginType=0">
          <span>运营管理</span>
          <span class="lower-line"></span>
        </div>
        <div class="nav-item" :class="{active:loginType==1}" @click="loginType=1;loginOrActive=1">
          <span>远程值班</span>
          <span class="lower-line"></span>
        </div>
        <div class="nav-item" :class="{active:loginType == 2}" @click="loginType = 2">
          <el-dropdown class="login-menu-dropdown" trigger="click" @command="handleCommand">
            <div class="link-box">
              <span>收费管理</span>
              <span class="lower-line"></span>
            </div>
            <el-dropdown-menu slot="dropdown" class="login-menu-dropdown-menu">
              <el-dropdown-item
                v-for="item in links"
                :key="item.name"
                :command="item.url"
              >{{ item.name }}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
    </div>

    <div class="login-box" v-if="loginType !== 2 && loginOrActive == 1">
      <div class="login-title">登录</div>
      <el-form
        label-position="top"
        label-width="80px"
        :model="loginForm"
        :rules="loginRules"
        ref="loginRuleForm"
        :show-message="showErroMsg"
      >
        <el-form-item label="  " prop="username">
          <el-autocomplete
            @keyup.enter.native="toLogin('loginRuleForm')"
            v-model="loginForm.username"
            :fetch-suggestions="querySearch"
            @keyupEnter="toLogin('loginRuleForm')"
            @select="handleSelect"
            tabindex="1"
            id="userName"
            placeholder="请输入账号"
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="  " prop="password">
          <el-input
            @keyup.enter.native="toLogin('loginRuleForm')"
            :type="passType"
            v-model="loginForm.password"
            @keyupEnter="toLogin('loginRuleForm')"
            tabindex="2"
            id="passWord"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="  " prop="validateCode">
          <el-input
            type="text"
            @keyup.enter.native="toLogin('loginRuleForm')"
            v-model="loginForm.validateCode"
            tabindex="3"
            id="validateCode"
            placeholder="请输入验证码"
          >
            <template slot="append">
              <img :src="seccodeSrc" alt title="点击换一张图片" @click="refreshCode()" />
            </template>
          </el-input>
        </el-form-item>

        <div class="btn-groups mt20">
          <el-checkbox v-model="remPass" tabindex="4">记住我</el-checkbox>
        </div>

        <div class="btn-groups-box">
          <el-button @click="toLogin('loginRuleForm')" tabindex="5">登录</el-button>
          <span class="reg-btn" @click="register" v-if="loginType == 0">点击注册>></span>
        </div>
      </el-form>
    </div>

    <div class="reg-box" v-show="loginOrActive==2">
      <div class="reg-title">注册</div>
      <!-- 注册-激活码框 -->
      <el-form
        label-position="top"
        label-width="80px"
        :model="activeCodeForm"
        :rules="activeCodeRules"
        ref="activeCodeRuleForm"
        v-show="!isShowRegForm"
      >
        <el-form-item label="激活码" prop="activeCode">
          <el-input
            v-model.trim="activeCodeForm.activeCode"
            type="text"
            id="activeCode"
            placeholder="请输入正确的激活码"
          ></el-input>
        </el-form-item>

        <div class="btn-groups-box">
          <el-button @click="validateActiveCode('activeCodeRuleForm')">下一步</el-button>
          <span class="goback-btn" @click="loginOrActive=1">返回登录>></span>
        </div>
      </el-form>

      <!-- 注册-注册框 -->
      <el-form
        label-position="top"
        label-width="80px"
        :model="regForm"
        :rules="regRules"
        ref="regRuleForm"
        v-show="isShowRegForm"
      >
        <el-form-item label="管理方名称" prop="nickname">
          <el-input
            v-model.trim="regForm.nickname"
            type="text"
            id="nickname"
            placeholder="请输入管理方名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="账号" prop="account">
          <el-input v-model.trim="regForm.account" type="text" id="account" placeholder="请输入登录账号"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model.trim="regForm.password"
            type="password"
            id="password"
            placeholder="请输入登录密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码确认" prop="password_confirm">
          <el-input
            v-model.trim="regForm.password_confirm"
            type="password"
            id="password_confirm"
            placeholder="请再次输入密码"
          ></el-input>
        </el-form-item>

        <el-button class="regForm-btn" @click="submitRegInfo('regRuleForm')">注册</el-button>
      </el-form>
    </div>

    <div class="functional-btn-groups"></div>
  </div>
</template>

<script>
import { mapGetters, mapMutations, mapState } from "vuex";
import theme from "../mixins/theme.js";
import crypto from "../mixins/crypto.js";
import utils from "../mixins/utils.js";
import InputSelectBox from "../components/widgets/InputSelectBox.vue";
import { setCookie, getCookie, deleteCookie } from "../assets/js/storage.js";
import { getByteLength, jsonToUrl } from "../assets/js/help.js";
import setting from "@/utils/setting.js";
import axios from "axios";
import md5 from "md5";
const sessionId = window.sessionStorage.getItem("_s");

export default {
  mixins: [theme, crypto, utils],
  data() {
    let self = this;
    let limitLength = (min, max, value) => {
      let len = getByteLength(value);
      if (len < min || len > max) {
        return false;
      }
      return true;
    };
    let validName = (rule, value, callback) => {
      if (value.length > 0) {
        if (!limitLength(5, 10, value)) {
          callback(new Error(rule.message));
          return;
        }
      }
      callback();
    };
    let validCode = (rule, value, callback) => {
      self.verifyCode(rule, value, callback);
    };
    let validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.regForm.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      redirectUrl: "#/", //重定向url
      version: setting.version,
      links: [],
      loginOrActive: 1, //1:登录 2:激活码
      loginType: 0,
      seccodeSrc: "",
      passType: "text",
      showErroMsg: true,
      activeCodeForm: {
        activeCode: "" //激活码
      },
      activeCodeRules: {
        activeCode: [
          {
            required: true,
            message: "激活码不能为空",
            trigger: "blur"
          }
        ]
      },
      regForm: {
        nickname: "", //管理方名称
        account: "", //登录账号
        password: "", //登录密码
        password_confirm: "" //再次输入密码
      },
      regRules: {
        nickname: [
          {
            required: true,
            message: "管理方名称不能为空",
            trigger: "blur"
          }
        ],
        account: [
          {
            required: true,
            message: "账号不能为空",
            trigger: "blur"
          }
        ],
        password: [
          {
            required: true,
            message: "密码不能为空",
            trigger: "blur"
          },
          {
            min: 6,
            max: 16,
            message: "长度在6到16个字符",
            trigger: "change,blur"
          }
        ],
        password_confirm: [
          {
            required: true,
            message: "密码不能为空",
            trigger: "blur"
          },
          {
            validator: validatePass,
            trigger: "blur"
          }
        ]
      },
      loginForm: {
        username: "",
        password: "",
        validateCode: ""
      },
      loginRules: {
        username: [
          {
            required: true,
            message: "用户名不能为空",
            trigger: "blur"
          }
          // { validator: validName, trigger: 'blur', message: '长度在5到10个字符' }
          // {min: 5, max: 10, message: '', trigger: 'blur,change'}
        ],
        password: [
          {
            required: true,
            message: "密码不能为空",
            trigger: "blur"
          },
          {
            min: 6,
            max: 16,
            message: "长度在6到16个字符",
            trigger: "change,blur"
          }
        ],
        validateCode: [
          {
            required: true,
            message: "验证码不能为空",
            trigger: "blur"
          },
          {
            validator: validCode,
            trigger: "change,blur",
            message: "验证码输入有误"
          }
        ]
      },
      curLang: 0,
      inputVal: "",
      accountVal: "",
      remPass: false,
      showTip: false,
      accountList: [],
      isShowRegForm: false
    };
  },
  components: {
    InputSelectBox
  },
  computed: {
    ...mapGetters({
      sysLanguage: "getSysLanguage"
    }),
    ...mapState(["logoObj"])
  },
  watch: {
    loginType: function() {
      this.loginForm.username = "";
      this.loginForm.password = "";
      this.refreshCode();
    }
  },
  created() {
    this.getSysUrl();
    window.localStorage.clear();
    window.sessionStorage.setItem("_t", "");
    window.localStorage.setItem("isLogout", 0);
    this.refreshCode();
    this.getUrlMsg("carrierId");
  },
  mounted() {
    this.initPage();
    this.$store.commit("LOADING_TOGGLE", false);
    this.passType = "password";
  },
  methods: {
    ...mapMutations({
      setLogoObj: "setLogoObj",
      setSkinType: "setSkinType"
    }),
    async getSysUrl() {
      const [central_url, sentry_url] = await Promise.all([
        this.fetchCentralChargePage(),
        this.fetchSentryChargePage()
      ]);
      this.links = [
        {
          name: "岗亭收费",
          url: sentry_url
        },
        {
          name: "中央收费",
          url: central_url
        }
      ];
    },
    fetchCentralChargePage() {
      return API.fetchGet("/payPage/getCentralChargePage");
    },
    fetchSentryChargePage() {
      return API.fetchGet("/payPage/getSentryChargePage");
    },
    handleCommand(url) {
      window.open(url);
    },
    //验证激活码
    validateActiveCode(formName) {
      let self = this;
      let activeCode = self.activeCodeForm.activeCode;
      this.$refs[formName].validate(valid => {
        if (valid) {
          let params = {
            code: activeCode
          };
          API.fetchGet("/normal/ajax/validateActivationCode.do", params).then(
            res => {
              self.showToast(res.message, 1, 3000);
              self.isShowRegForm = true;
            },
            err => {
              let data = err.data;
              self.showToast(data.message, 2, 3000);
            }
          );
        }
      });
    },
    register() {
      this.loginOrActive = 2;
      for (let key in this.regForm) {
        console.log(key);
        this.regForm[key] = "";
      }
    },
    //提交注册信息
    submitRegInfo(formName) {
      let self = this;
      let nickname = self.regForm.nickname;
      let account = self.regForm.account;
      let password = self.regForm.password;
      let password_confirm = self.regForm.password_confirm;
      let activeCode = self.activeCodeForm.activeCode;
      this.$refs[formName].validate(valid => {
        if (valid) {
          let aparams = {
            loginId: account
          };
          API.fetchPost("/normal/ajax/validUser.do", aparams).then(
            res => {
              let data = res;
              if (data == false) {
                self.showToast("账号已被占用", 2);
                return;
              } else if (data == true) {
                let paramsReg = {
                  managerName: nickname,
                  userAccount: account,
                  firstPwd: password,
                  confirmPwd: password_confirm,
                  activationCode: activeCode
                };
                API.fetchPost("/normal/ajax/registerUser.do", paramsReg).then(
                  res => {
                    self.showToast(res.message, 1);
                    self.activeCodeForm.activeCode = "";
                    self.regForm.nickname = "";
                    self.regForm.account = "";
                    self.regForm.password = "";
                    self.regForm.password_confirm = "";
                    self.isShowRegForm = false;
                    self.loginOrActive = 1;
                    if (res.data) {
                      window.location.href = res.data;
                      return;
                    }
                  },
                  err => {
                    self.showToast(err.data.message, 2);
                  }
                );
              }
            },
            err => {}
          );
        }
      });
    },
    // 获取自定义图片的参数
    getUrlMsg(key) {
      let href = window.location.hash;
      // href = "http://10.10.18.25:6002/#/Book/BookNow?carrierId=6";
      let str = href.split("?")[1];

      if (str) {
        let val;
        str.split("&").forEach((element, index) => {
          if (element.split("=")[0] == key) {
            val = element.split("=")[1];
          }
        });
        if (!val) {
          //url找不到_carrierId
          val = getCookie("_carrierId");
        }
        window.sessionStorage.setItem("_carrierId", val);
      } else {
        let Obj = {
          logoImg: null,
          loginImg: null,
          homepageImg: null
        };
        let val = getCookie("_carrierId");
        window.sessionStorage.setItem("_carrierId", val);
        window.sessionStorage.setItem("_LogoObj", JSON.stringify(Obj));
      }
      this.getLogoObj();
    },
    initPage() {
      window.sessionStorage.removeItem("thisTab");
      let _u = window.localStorage.getItem("_u");
      this.getPassVal(_u);
    },
    getPassVal(name) {
      let _pass = getCookie(name);
      _pass = this.getPwd(_pass);
      this.loginForm.username = name;
      this.loginForm.password = _pass;
      if (_pass !== "") {
        this.remPass = true;
      }
    },
    verifyCode(rule, value, callback) {
      let self = this,
        isValid = false;
      if (self.loginType == 1) {
        callback();
        return;
      }
      API.login.VerifyCode(value).then(
        res => {
          isValid = res.valid;
          if (!isValid) {
            callback(new Error(rule.message));
            self.refreshCode(); //验证失败 重新获取验证码
          }
          callback();
        },
        err => {
          callback(new Error(rule.message));
        }
      );
    },
    refreshCode() {
      // 0 运营商登录 1 中央值守登录
      let src = "";
      let _loginSessionId = new Date().getTime();
      if (this.loginType == 0) {
        src = "mgr/normal/authz/seccode.do?_=";
      }
      if (this.loginType == 1) {
        src =
          "/zbcloud/user-service/cenduty/seat/getVerificationCode?sessionId=";
      }
      src += _loginSessionId;
      window.sessionStorage.setItem("_loginSessionId", _loginSessionId);
      this.seccodeSrc = src;
    },
    handleSelect(item) {
      this.getPassVal(item.value);
    },
    querySearch(queryString, cb) {
      var accountList = this.accountList;
      var results = queryString
        ? accountList.filter(this.createFilter(queryString))
        : accountList;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return accountList => {
        return accountList.value.indexOf(queryString.toLowerCase()) === 0;
      };
    },
    indexOfObjArr(name, objArr) {
      for (let i = 0, len = objArr.length; i < len; i++) {
        if (name == objArr[i].value) {
          return i;
        }
      }
      return -1;
    },
    toLogin(formName) {
      let self = this;
      let username = self.loginForm.username;
      let password = self.loginForm.password;
      let _pass = self.setPwd(self.loginForm.password);
      let seccode = self.loginForm.validateCode;

      this.$refs[formName].validate(valid => {
        if (valid) {
          let params = {
            username: username,
            password: password,
            seccode: seccode
          };
          // 中央值守登录————判断
          if (this.loginType === 1) {
            API.fetchPost(
              "/zbcloud/user-service/cenduty/seat/login",
              {
                userid: params.username,
                password: md5(params.password),
                validateCode: seccode, //  验证码
                sessionId: window.sessionStorage.getItem("_loginSessionId") //每次验证码都不一样
              },
              {
                baseURL: "/"
              }
            ).then(
              response => {
                let _t = response.message.split(";")[0];
                let _pd = response.message.split(";")[1];
                let _url = response.message.split(";")[2];
                let topOperatorId = response.message.split(";")[3];

                let monitorIndexUrl =
                  _url +
                  "/?t=" +
                  new Date().getTime() +
                  "#/?_t=" +
                  _t +
                  "&_pd=" +
                  _pd +
                  "&_linkUrl=" +
                  window.location.origin +
                  "&_top=" +
                  topOperatorId;
                if (topOperatorId) {
                  API.fetchGet(
                    _url +
                      "/zbcloud/center-monitor-service/zbcloud-grey/api/execute",
                    {
                      topOperatorId: topOperatorId
                    },
                    {
                      withCredentials: true
                    }
                  )
                    .then(response => {
                      window.location.href = monitorIndexUrl;
                    })
                    .catch(error => {
                      window.location.href = monitorIndexUrl;
                    });
                }
              },
              err => {}
            );
            return;
          }
          API.login.Login(params).then(
            async res => {
              if (res.status == 1) {
                let _ul = [];
                _ul.push({
                  value: username
                });
                window.localStorage.removeItem("_ul");
                window.localStorage.setItem("_ul", JSON.stringify(_ul));
                if (self.remPass) {
                  setCookie(username, _pass);
                } else {
                  deleteCookie(username);
                }
                window.localStorage.setItem("isLogout", 2);
                window.localStorage.setItem("getSessionStorage", Date.now());
                await self.getIndexPageUrl();

                //灰度发布
                var user = res.data;

                API.login
                  .zbcloudGrey(user)
                  .then(res => {
                    //重定向
                    window.location.href =
                      "/?t=" + new Date().getTime() + self.redirectUrl;
                  })
                  .catch(error => {
                    window.location.href =
                      "/?t=" + new Date().getTime() + self.redirectUrl;
                  });
              }
            },
            err => {
              self.refreshCode();
            }
          );
        } else {
          return false;
        }
      });
    },
    selectedOne() {
      let returnArr = arguments;
      this.username = returnArr[0];
      this.accountVal = returnArr[1];
    },
    focusPass(e) {
      //先把密码框的类型设为text,在focus的时候再将其转为password
      //目的是不让浏览器提示自动记住密码，非password的type浏览器是不会提示记录的
      let $Target = $(e.target);
      $Target.attr("type", "password");
    },
    getSkinConfig(aparams) {
      let self = this,
        params = {};
      params = $.extend({}, params, aparams);
      API.login.getSkinConfig(params).then(
        res => {
          let data = res.data;

          self.setLogoObj(data);
        },
        err => {}
      );
    },
    // 获取菜单权限信息
    async getIndexPageUrl() {
      let self = this;
      const [menusRes, parkingRes] = await Promise.all([
        this.fetchMenus(),
        this.fetchCurUserParkingLot()
      ]);
      if (
        parkingRes.parks === null ||
        (Array.isArray(parkingRes.parks) && parkingRes.parks.length === 0)
      ) {
        self.redirectUrl = "#/addParkingLot";
        return;
      }
      if (menusRes.menus && menusRes.menus.length > 0) {
        self.setIndexPage(menusRes.menus); //获取首页url
      }
    },
    // 获取菜单
    fetchMenus() {
      return API.fetchGet("/main/newmenu.do", {});
    },
    // 获取当前登录用户所属停车场
    fetchCurUserParkingLot() {
      return API.fetchGet("/main/getParks.do", {});
    },
    //获取首页url
    setIndexPage(menuList) {
      const indexPageData = menuList[0];
      if (indexPageData.name === "首页") {
        this.redirectUrl = "#/index";
      } else {
        const path = this.getPath(indexPageData);
        this.redirectUrl = "#" + path;
      }
    },
    // 递归获取首页url
    getPath(indexPageData) {
      if (indexPageData.childList.length) {
        return this.getPath(indexPageData.childList[0]);
      } else {
        return indexPageData.url;
      }
    }
  }
};
</script>

<style lang="less">
@import "../assets/less/base/form.less";
@import "../assets/less/base/button.less";
@import "../assets/less/login.less";

.login-right-box {
  form.el-form.el-form--label-top {
    flex: 5;
  }

  .el-form-item .el-form-item__label {
    padding: 16px 0;
  }

  .el-form-item {
    margin-bottom: 0px;
  }

  .mt50 {
    margin-top: 38px;
  }
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}

.fade-enter,
.fade-leave-active {
  opacity: 0;
}

.form-group .login-tip {
  margin-top: @spacing;

  i {
    color: @red;
    margin-right: @spacing;
  }
}

.mt50 {
  margin-top: 50px;
}

.mt20 {
  margin-top: 20px;
}

.login-wrapper .el-form-item.is-required .el-form-item__label {
  width: 100%;
  color: #fff; //label颜色
  height: 27px;
  line-height: 20px;

  &:before {
    display: none;
  }
}

.btn-groups-box {
  .el-button {
    background: #5995d8;
  }
}
</style><style lang="css">
.el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label:before {
  display: none;
}
</style>
